<template>
  <MainSlot>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <el-table ref="tableData" v-loading="loading" highlight-current-row :data="tableData" stripe border height="92%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="60" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column v-for="item,index in formDataLists" :key="index" :prop="item.porp" :label="item.name" :min-width="130">
          <!-- <template v-if="!item.notSearch" #header>
            <TypePopover v-if="tableUpStauts === 1" :column-index="index" :column="item" :filter-options="item.typeObj.list" :filter-name="item.typeObj.listName" :table-up-stauts="tableUpStauts" @tableUpdate="tableUpdate($event, item.name)" />
          </template> -->
          <template v-if="scope.row.equipmentNo" slot-scope="scope">
            <span v-if="item.name === '饲喂量'">{{ scope.row[item.porp] }}{{ scope.row.symbol || scope.row.unitName }}</span>
            <span v-else-if="item.porpName === 'time'">{{ scope.row.startTime }}--{{ scope.row.endTime }}</span>
            <span v-else>{{ scope.row[item.porp] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120">
          <template v-if="scope.row.equipmentNo" slot-scope="scope">
            <el-button type="text" class="text-btn-cursor" size="small" @click.stop="edit(scope.row)">
              <i class="el-icon-edit-outline"></i>修改
            </el-button>
            <el-button type="text" class="text-btn-cursor cursor-delete" size="small" @click="numberDel(scope.row)">
              <i class="el-icon-delete"></i>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="handleCurrentChange" :page="currentPage" :total="totalSize">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog v-loading="loading" width="50%" :title="titleText + '设备'" :visible.sync="dialogFormVisible" @close="cancel('formData')">
        <el-form ref="formData" label-position="left" :model="formData" label-width="120px" :rules="rules"
          class="el-form">
          <el-form-item  label="设备类型:" class="w50p " :prop="'type'">
            <el-select  class="w100p"  ref="type" v-model="formData.type" clearable>
              <el-option label="电表" value="电表" />
              <el-option label="水表" value="水表" />
            </el-select>
          </el-form-item>
          <el-form-item label="数据项选择:" prop="dataItemId" class="w50p">
            <el-select   class="w100p"  v-model="formData.dataItemId" placeholder="请选择数据项" filterable clearable @change="(e) => {
                let index = Array.isArray(dataItemList) ? dataItemList.findIndex(item => item.dataItemId === e) : -1;
                if (index !== -1) {
                  $set(formData, 'equipmentName', dataItemList[index].originalName);
                }
              }">
              <el-option v-for="item in dataItemList" :key="item.dataItemId" :label="item.originalName" :value="item.dataItemId" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备名称 :" :prop="'equipmentName'" class="w50p">
            <el-input   class="w100p"  v-model="formData.equipmentName" placeholder clearable />
          </el-form-item>

          <el-form-item label="备注 :" :prop="'remarks'" class="w50p">
            <el-input   class="w100p"  v-model="formData.remarks" placeholder clearable />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保存</el-button>
        </span>
      </el-dialog>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import Pagination from "@/components/Pagination";
import SearchBox from "@/components_yy/SearchBox";
import TypePopover from "@/components_yy/ZnFilterTable/typePopover.vue";
import BtnSlot from "@/components/BtnSlot";
import { mymixin } from "@/utils/mixins";
import Api from "@/api/livestock-manage/energy-management/deviceApi";
// import dataItemApi from "@/api/basic-info-manage/data-item-management";
export default {
  name: "BreedRecord",
  components: {
    MainSlot,
    Pagination,
    SearchBox,
    BtnSlot,
    TypePopover,
  },
  mixins: [mymixin],
  data() {
    return {
      batchList: [],
      materialList: [],
      nowIndex: "",
      selectType: "single",
      initialParameters: {},
      sheepList: [],
      unitList: [], // 单位
      loading: false,
      nowChanceStau: "",
      dialogFormVisible: false,
      noList: [], // 批量删除列表
      personList: [], // 记录人列表
      sheepBulidingList: [], // 羊舍
      formData: {},
      btnList: ["add", "delete"],
      dataItemList: [],
      formDataLists: [
        {
          type: "Select", // input Select Checkbox TimePicker
          porp: "type",
          selectValue: "type",
          typeObj: {
            list: [
              {
                name: "电表",
                value: "电表",
              },
              {
                name: "水表",
                value: "水表",
              },
            ],
          },
          name: "设备类型",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "equipmentName",
          typeObj: {},
          name: "设备名称",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "originalName",
          selectValue: "originalName",
          typeObj: {},
          name: "数据项",
          required: true,
          notSearch: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "remarks",
          typeObj: {},
          name: "备注",
          required: true,
          notSearch: true,
        },
      ],
      rules: {
        equipmentName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" },
        ],
        dataItemId: [
          { required: true, message: "数据项不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getDataItemList();
    this.getTableDataList()
  },
  mounted() {},
  methods: {
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "add") {
        this.formData = {  };
      this.nowChanceStau = "add";
      this.titleText = "添加";
      this.dialogFormVisible = true;
      } else if (flag == "delete") {
        if (this.noList.length > 0) {
          this.delmessage(this.noList);
        } else {
          this.$message.warning("请先选择表单数据项后再删除！");
        }
      }
      this.addEditFlag = flag;
    },
    getDataItemList() {
      Api.getDataItem({ organizationNo: sessionStorage.organizationNo }).then(
        (res) => {
          // console.log(res.data)
          if (res.code === 1 && res.data !== undefined) {
            this.dataItemList = res.data;
          }
        }
      );
    },
    // 获取表单数据
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...this.searchObj,
          startTime:
            this.searchObj?.feedTime === undefined
              ? ""
              : this.searchObj.feedTime + " 00:00:00",
          endTime:
            this.searchObj?.feedTime === undefined
              ? ""
              : this.searchObj.feedTime + " 23:59:59",
        },
      };
      delete params.entity?.feedTime;
      Api.pageQuery(params).then((res) => {
        this.loading = false;
        if (res.code === 1) {
          this.tableData = JSON.parse(JSON.stringify(res.data.content));
          this.totalSize = res.data.totalElements;
          this.addblankmet();
        }
      });
    },
    handleSelectionChange(list) {
      this.noList = [];
      this.noList = list.map((item) => item.equipmentNo);
      if (this.noList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    edit(row) {
      this.formData = { ...row };
      this.nowChanceStau = "edit";
      this.titleText = "修改";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    // 单个删除
    numberDel(row) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          let params = row.equipmentNo;
          Api.numberDel(params).then((res) => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    // 批量删除
    delmessage() {
      Api.numberBatchDel({
        noList: this.noList,
      }).then((res) => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.getTableDataList();
        } else {
          this.$message.warning(res.msg || "删除失败");
        }
      });
    },
    save(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          console.log(this.formData);
          if (this.nowChanceStau === "edit") {
            Api.edit(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.$refs[formData].resetFields();
                this.getTableDataList();
                this.dialogFormVisible = false;
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            Api.add(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success("新增成功！");
                this.$refs[formData].resetFields();
                this.getTableDataList();
                this.dialogFormVisible = false;
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.lookfacility {
  display: flex;
  div {
    font-size: 20px;
    padding: 5px 10px;
    background-color: #d6ebff;
    margin-right: 10px;
    border-radius: 6px;
  }
}
::v-deep .feed {
  display: flex !important;
  .feedOne {
    width: 65%;
  }
  .feedTwo {
    width: 35%;
  }
}
.line {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  .line-click {
    width: 30px;
    height: 30px;
    background-color: rgb(198, 196, 196);
    display: flex;
    justify-content: center;
    align-items: center;
    border: rgb(214, 214, 214) 1px solid;
    border-radius: 50%;
    margin-bottom: 10px;
    margin-top: 5px;
    margin-left: 5px;
    cursor: pointer;
    .el-icon-minus {
      color: white;
    }
  }
}
.line-click {
  width: 30px;
  height: 30px;
  background-color: rgb(198, 196, 196);
  display: flex;
  justify-content: center;
  align-items: center;
  border: rgb(214, 214, 214) 1px solid;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 120px;
  cursor: pointer;
  .el-icon-plus {
    color: white;
  }
}
::v-deep .w30p {
  width: 33% !important;
}
::v-deep .w100p {
  width: 96.5% !important;
}
.feedmount {
  display: flex;
  justify-content: space-between;
}
.el-form{
  display: flex;
  flex-wrap: wrap;
}
</style>
